package com.ezjie.ielts.module_word;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.ezjie.ielts.R;
import com.ezjie.ielts.application.YsApplication;
import com.ezjie.ielts.core.base.BaseBean;
import com.ezjie.ielts.core.http.HttpRequestAbstractCallBack;
import com.ezjie.ielts.model.StudyRecord;
import com.ezjie.ielts.model.WordBean;
import com.ezjie.ielts.model.WordStudyStatus;
import com.ezjie.ielts.module_word.adapter.WordFirstStudyDetailAdapter;
import com.ezjie.ielts.task.WordTask;
import com.ezjie.ielts.util.AppUtil;
import com.ezjie.ielts.util.DensityUtil;
import com.ezjie.ielts.util.ListUtils;
import com.ezjie.ielts.util.LogUtils;
import com.ezjie.ielts.util.NetworkUtil;
import com.ezjie.ielts.util.PlayAnimationUtils;
import com.ezjie.ielts.util.SpeechTTSUtil;
import com.ezjie.ielts.util.UmengPages;
import com.ezjie.ielts.util.WordHomeDataUtil;
import com.ezjie.ielts.view.AutofitTextView;
import com.ezjie.ielts.view.stikkyheader.StikkyHeaderBuilder;
import com.lidroid.xutils.exception.HttpException;
import com.umeng.analytics.MobclickAgent;

/**
 * 第一次学习界面 单词的解析
 * 
 * @author renyangyang
 *
 */
public class WordFirstStudyDetailFragment extends Fragment implements OnClickListener {
	private static final String TAG = WordFirstStudyDetailFragment.class.getSimpleName();
	private WordBean wordBean;
	private AutofitTextView tv_word;
	private ScrollView scrollView;
	private TextView tv_phonetic;
	private TextView tv_explanes;
	private ListView lv_examples;
	private Button btn_ok;
	private TextView tv_explaneHint;// 让焦点在最上面
	private LinearLayout ll_speak;

	private ImageView iv_speak;
	private AnimationDrawable animation;
	private AnimationDrawable animation2;

	private WordFirstStudyDetailAdapter adapter;
	private WordStudyStatus wordStudyStatus;
	private int max;
	private int progress;
	private int status;
	private int wgid;
	private List<StudyRecord> studyRecords;
	private boolean isPause;// 是退出 还是提交
	private WordTask mWordTask;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		animation = PlayAnimationUtils.PlayWordAnimation(getActivity());
		animation2 = PlayAnimationUtils.PlayWordAnimation(getActivity());
		SpeechTTSUtil.getInstance(getActivity()).init();
		mWordTask = new WordTask(getActivity());
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.layout_word_first_study_detail, container, false);
		init(view);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		StikkyHeaderBuilder.stickTo(scrollView).setHeader(R.id.ll_word, (FrameLayout) getView())
				.minHeightHeader(DensityUtil.dip2px(getActivity(), 0)).build();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPageEnd(UmengPages.PAGE_WORD_FIRST_DTUDY_DETAIL);
		MobclickAgent.onPause(getActivity());
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onPageStart(UmengPages.PAGE_WORD_FIRST_DTUDY_DETAIL);
		MobclickAgent.onResume(getActivity());
	}

	private void init(View view) {
		if (getActivity() != null) {

			tv_word = (AutofitTextView) view.findViewById(R.id.tv_word);
			tv_word.setOnClickListener(this);
			tv_phonetic = (TextView) view.findViewById(R.id.tv_phonetic);
			tv_explanes = (TextView) view.findViewById(R.id.tv_explanes);
			lv_examples = (ListView) view.findViewById(R.id.lv_examples);
			lv_examples.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					if (wordBean == null) {
						return;
					}
					ImageView iv_speak = (ImageView) view.findViewById(R.id.iv_speak);
					if (animation2 != null && animation2.isRunning()) {
						animation2.selectDrawable(0);
						animation2.stop();
					}
					if (animation != null && animation.isRunning()) {
						animation.selectDrawable(0);
						animation.stop();
					}
					animation2 = PlayAnimationUtils.PlayWordAnimation(getActivity());
					iv_speak.setImageDrawable(animation2);
					animation2.start();
					String sentence_text = wordBean.getInstances().get(position).getOrigin();
					if (!TextUtils.isEmpty(sentence_text)) {
						SpeechTTSUtil.getInstance(getActivity()).speak(sentence_text, animation2);
					}

				}
			});
			btn_ok = (Button) view.findViewById(R.id.btn_ok);
			btn_ok.setOnClickListener(this);
			tv_explaneHint = (TextView) view.findViewById(R.id.tv_explaneHint);
			scrollView = (ScrollView) view.findViewById(R.id.scrollView);
			ll_speak = (LinearLayout) view.findViewById(R.id.ll_speak);
			ll_speak.setOnClickListener(this);
			iv_speak = (ImageView) view.findViewById(R.id.iv_speak);

			adapter = new WordFirstStudyDetailAdapter(getActivity());

			initData();

		}
	}

	private void initData() {
		YsApplication myApplication = (YsApplication) getActivity().getApplication();
		studyRecords = myApplication.getStudyRecords();

		wordBean = myApplication.getWordBean();
		wordStudyStatus = myApplication.getWordStudyStatus();
		if (wordStudyStatus != null) {
			max = wordStudyStatus.getMax();
			progress = wordStudyStatus.getProgress();
			status = wordStudyStatus.getStatus();
			wgid = wordStudyStatus.getWgid();
		}

		if (wordBean != null) {
			tv_word.setText(Html.fromHtml(wordBean.getWord()));
			if (!TextUtils.isEmpty(wordBean.getPhonetic()) && !"[]".equals(wordBean.getPhonetic())) {
				ll_speak.setVisibility(View.VISIBLE);
				tv_phonetic.setText(Html.fromHtml(wordBean.getPhonetic()));
			} else {
				ll_speak.setVisibility(View.INVISIBLE);
			}
			tv_explanes.setText(Html.fromHtml(ListUtils.getTransferStrByList(wordBean.getMeans())));
			adapter.setList(wordBean.getInstances());
			adapter.setKeyword(wordBean.getWord());
			lv_examples.setAdapter(adapter);

			initParentProgress();

			tv_explaneHint.setFocusable(true);
			tv_explaneHint.setFocusableInTouchMode(true);
			tv_explaneHint.requestFocus();

		}
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		// TODO Auto-generated method stub
		super.onHiddenChanged(hidden);
		if (!hidden) {
			// 每次切换界面的时候 都重新获得数据
			initData();
		}
	}

	private void initParentProgress() {
		// 控制父view显示进度
		Activity parentActivity = getActivity();
		if (parentActivity instanceof WordStudyManagerActivity) {
			WordStudyManagerActivity activity = (WordStudyManagerActivity) parentActivity;
			activity.showProgress(max, progress);
		}
	}

	private void changeView() {
		// 控制父view显示详情
		Activity parentActivity = getActivity();
		if (parentActivity instanceof WordStudyManagerActivity) {
			WordStudyManagerActivity activity = (WordStudyManagerActivity) parentActivity;
			SpeechTTSUtil.getInstance(getActivity()).pause();
			activity.showView(WordStudyManagerActivity.SHOW_WORD);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_ok:
			if (getActivity() != null) {
				if (progress == max) {
					// 调到summary界面
					LogUtils.d("第一次练习结束，该交卷了，哈哈");
					isPause = false;
					saveProgress();

				} else {
					changeView();
				}

			}
			break;
		case R.id.ll_speak:
		case R.id.tv_word:
			iv_speak.setImageDrawable(animation);
			animation.start();
			if (animation2 != null && animation2.isRunning()) {
				animation2.selectDrawable(0);
				animation2.stop();
			}
			String string = tv_word.getText().toString();
			if (!TextUtils.isEmpty(string)) {
				SpeechTTSUtil.getInstance(getActivity()).speak(string, animation);
			}
			break;
		case R.id.navi_back_btn:
			onBackPressed();
			break;
		default:
			break;
		}
	}

	public void onBackPressed() {
		if (getActivity() != null) {

			View view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_rob_warn_dialog, null);

			final Dialog dialog = new Dialog(getActivity(), R.style.customDialog);
			dialog.setCanceledOnTouchOutside(false);
			dialog.setContentView(view);
			dialog.show();

			TextView tv_content = (TextView) view.findViewById(R.id.tv_content);
			tv_content.setText(R.string.word_first_exit_msg);
			LinearLayout ll_layout1 = (LinearLayout) view.findViewById(R.id.ll_layout1);
			LinearLayout ll_layout2 = (LinearLayout) view.findViewById(R.id.ll_layout2);
			ll_layout1.setVisibility(View.VISIBLE);
			ll_layout2.setVisibility(View.GONE);

			Button btn_yes = (Button) view.findViewById(R.id.btn_yes);
			Button btn_no = (Button) view.findViewById(R.id.btn_no);
			btn_no.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (getActivity() != null && dialog != null && dialog.isShowing()) {
						dialog.cancel();
					}
				}
			});
			btn_yes.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (getActivity() != null && dialog != null && dialog.isShowing()) {
						dialog.cancel();
						// 友盟统计
						MobclickAgent.onEvent(getActivity(), "word_learning_backBtn");
						// 保存进度
						isPause = true;
						saveProgress();
					}

				}
			});

		}

	}

	private void saveProgress() {
		if (studyRecords == null) {
			studyRecords = new ArrayList<StudyRecord>();
		}
		if (getActivity() != null) {
			if (!NetworkUtil.isNetworkAvailable(getActivity())) {
				AppUtil.showToast(getActivity(), R.string.no_network);
				return;
			}

			mWordTask.saveProgress(wgid + "", isPause + "", status + "", JSON.toJSONString(studyRecords),
					new HttpRequestAbstractCallBack(getActivity(),true) {
						@Override
						public void onStartCallBack() {
							super.onStartCallBack();
							AppUtil.showProgressDialog(getActivity());
						}

						@Override
						public void onSuccessCallBack(String result) {
							super.onSuccessCallBack(result);
							LogUtils.d(result);
							AppUtil.dismissProgressDialog();
							try {
								BaseBean baseBean = JSON.parseObject(result, BaseBean.class);
								if (baseBean != null && 200 == baseBean.getStatus_code()) {
									// 提交成功
									if (getActivity() != null) {
										if (isPause) {
											Intent intent = getActivity().getIntent();
											intent.putExtra("isOver", true);
											getActivity().setResult(Activity.RESULT_OK, intent);
											SpeechTTSUtil.getInstance(getActivity()).close();
											getActivity().finish();
										} else {
											// 到summary界面
											WordHomeDataUtil.putTodayStudying(getActivity(), 0);
											WordHomeDataUtil.putTodayStudied(getActivity());
											WordHomeDataUtil.putReviewNum(getActivity(), 1);

											Intent intent = new Intent(getActivity(),
													WordFirstStudySummaryActivity.class);
											startActivity(intent);
											SpeechTTSUtil.getInstance(getActivity()).close();
											getActivity().finish();
										}
									}
								} else {
									if (getActivity() != null) {
										AppUtil.showToast(getActivity(), R.string.load_net_data_failure);
									}
								}
							} catch (Exception e) {
								LogUtils.d("json数据异常");
								LogUtils.exception(e);
							}
						}

						@Override
						public void onFailureCallBack(HttpException error, String msg) {
							super.onFailureCallBack(error, msg);
							LogUtils.e(msg);
							AppUtil.dismissProgressDialog();
							AppUtil.showToast(getActivity(), R.string.load_net_data_failure);
						}
					});
		}

	}

}
